package com.nuanshui.heatedloan.dao.cms.security;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.nuanshui.heatedloan.aliases.IdTypeHandler;
import com.nuanshui.heatedloan.entity.cms.security.User;
import com.nuanshui.heatedloan.entity.cms.security.UserVO;
import com.nuanshui.heatedloan.extension.hibernate.HibernateUtils;



@Component
public class securityDaoImpl {

	@Autowired
	private HibernateUtils hibernateUtils;
	
	@Autowired
	private JdbcTemplate  jdbcTemplate;
	
	
	/**
	 * 查询所有的用户
	 * @return
	 */
	public List<UserVO> listUsers(){
		String sql = " select * from cms_security_user ";
		
	return 	jdbcTemplate.queryForList(sql, UserVO.class);
		
	}


	public User loadAdminUserByForntUserId(String id) {
		long userId = IdTypeHandler.decode(id);
		String sql = " select * from cms_security_user where id = (select admin_user_id from front_user_admin_user where front_user_id = " + userId + " and archive = 0)";
		User adminUser = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class));
		return adminUser;
	}
	
	/**
	 * 获取app端的用户id，根据后端的用户查找中间表
	 * @author Gonzo
	 * @date 2017年1月12日下午8:12:55
	 * @param userId
	 * @return
	 * @since 1.0.0
	 */
	public Integer loadFrontUserIdByAdminUserId(long userId){
		String sql = " select front_user_id from front_user_admin_user where admin_user_id = '" + userId + "' and archive = 0";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

	
	/**
	 * 创建一个默认的管理员
	 * @author Gonzo
	 * @date 2017年1月12日下午4:27:54
	 * @param adminUserId
	 * @param frontUserId
	 * @since 1.0.0
	 */
	public Long createDefaultAdminUserByFrontUserId(Long adminUserId,String frontUserId) {

		//生成中间表
		jdbcTemplate.execute("insert into front_user_admin_user(admin_user_id, front_user_id, created_at, archive) values("
				+ adminUserId + ", " + IdTypeHandler.decode(frontUserId) + ", now(), " + " 0)");
		return adminUserId;
	}


	public void deleteAdminUserByFrontUserId(String frontUserid) {
		jdbcTemplate.execute("delete from front_user_admin_user where front_user_id = " + IdTypeHandler.decode(frontUserid) + " and archive = 0");
		
	}


	public void updateUserStatusToDisAble(String userId) {
		String sql = "delete from cms_security_user where id = (select admin_user_id from front_user_admin_user where front_user_id = " + IdTypeHandler.decode(userId) + " and archive = 0)";
		jdbcTemplate.execute(sql);
	}
	
	public void updateUserNick(String id,String nick) {
		String sql = "update cms_security_user set nick = '" + nick + "' where id = '" + id + "'";
		jdbcTemplate.execute(sql);
	}
	
}
